<template>
	<view class="addDevice">
		<view
			class="addDevice-content ff-margin-12 ff-padding-top-15 ff-padding-bottom-15 ff-padding-left-10 ff-padding-right-10 ff-bg-fff ff-border-radius-10 ff-color-333 ff-font-14">
			<view class="ff-font-16 ff-font-weight-600 ff-padding-bottom-10 ff-solid-bottom">添加新设备</view>
			<view class="ff-flex-between ff-align-items-one ff-padding-top-15 ff-padding-bottom-15 ff-solid-bottom">
				<view>设备名称</view>
				<view @click="deviceClick">
					<view v-if="!params.deviceName" class="ff-align-items-one">
						<view class="ff-color-BCBFCC ff-margin-right-2">请选择设备</view>
						<view><u-icon name="arrow-right" color="#B5BBC8" size="28"></u-icon></view>
					</view>
					<view v-else class="ff-align-items-one">
						<view class="ff-margin-right-2">{{ params.deviceName }}</view>
						<view v-if="!params.deviceId"><u-icon name="arrow-right" color="#333" size="28"></u-icon></view>
					</view>
					<!-- 弹框 -->
					<u-select v-model="deviceState" mode="single-column" :list="deviceList"
						:safe-area-inset-bottom="true" label-name="deviceName" value-name="id" title="选择设备"
						@confirm="deviceConfirm"></u-select>
				</view>
			</view>
			<view class="ff-flex-between ff-align-items-one ff-padding-top-15 ff-padding-bottom-15 ff-solid-bottom"
				v-if="params.facilitiesDeviceId == 9999">
				<view>自定义设备名称</view>
				<input type="text" v-model.trim="customName" class="ff-text-right ff-margin-right-8"
					placeholder="请输入自定义设备名称" placeholder-style="color: #B5BBC8" />
			</view>
			<view class="ff-flex-between ff-align-items-one ff-padding-top-15 ff-padding-bottom-15 ff-solid-bottom">
				<view>设备数量</view>
				<view class="ff-align-items-one">
					<input type="number" v-model.trim="params.deviceNum" class="ff-text-right ff-margin-right-8"
						placeholder="请输入设备数量" placeholder-style="color: #B5BBC8" />
					<view>个</view>
				</view>
			</view>
			<view class="ff-flex-between ff-align-items-one ff-padding-top-15 ff-padding-bottom-15 ff-solid-bottom">
				<view>设备编号</view>
				<input type="text" v-model.trim="params.deviceCode" class="ff-text-right ff-margin-right-10"
					placeholder="请输入设备编号" placeholder-style="color: #B5BBC8" />
			</view>
			<view class="ff-flex-between ff-align-items-one ff-padding-top-15 ff-padding-bottom-15 ff-solid-bottom">
				<view>设备购买时间</view>
				<view @click="timeClick">
					<view v-if="!params.deviceBuyTime" class="ff-align-items-one">
						<view class="ff-color-BCBFCC ff-margin-right-2">请选择设备购买时间</view>
						<view><u-icon name="arrow-right" color="#B5BBC8" size="28"></u-icon></view>
					</view>
					<view v-else class="ff-align-items-one">
						<view class="ff-margin-right-2">{{ params.deviceBuyTime }}</view>
						<view><u-icon name="arrow-right" color="#333" size="28"></u-icon></view>
					</view>
					<!-- 时间选择的弹框 -->
					<u-picker mode="time" title="设备购买时间" v-model="timeState" @confirm="confirmTimeClick"
						:default-time="params.deviceBuyTime" :params="timeParams"></u-picker>
				</view>
			</view>
			<view class="ff-padding-top-15 ff-padding-bottom-15 ff-solid-bottom">
				<view class="ff-margin-bottom-15">设备证书图片</view>
				<view>
					<u-row gutter="20">
						<u-col span="3" v-for="(item, index) of params.certificatePics" :key="index">
							<view class="deviceImg ff-margin-bottom-10" @click="previewImgClick(item, 1)">
								<image :src="item" mode="" />
								<view @click.stop="deteleImgClick(index, 1)" class="closeIcon"><u-icon name="close"
										color="#fff" size="22"></u-icon></view>
							</view>
						</u-col>
						<u-col span="3">
							<image @click="upateImgClick(1)"
								src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/upate-icon.png"
								mode="" />
						</u-col>
					</u-row>
				</view>
			</view>
			<view class="ff-padding-top-15 ff-padding-bottom-15 ff-solid-bottom">
				<view class="ff-margin-bottom-15">设备发票图片</view>
				<view>
					<u-row gutter="20">
						<u-col span="3" v-for="(item, index) of params.invoicePics" :key="index">
							<view class="deviceImg ff-margin-bottom-10" @click="previewImgClick(item, 2)">
								<image :src="item" mode="" />
								<view @click.stop="deteleImgClick(index, 2)" class="closeIcon"><u-icon name="close"
										color="#fff" size="22"></u-icon></view>
							</view>
						</u-col>
						<u-col span="3">
							<image @click="upateImgClick(2)"
								src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/upate-icon.png"
								mode="" />
						</u-col>
					</u-row>
				</view>
			</view>
			<view class="ff-padding-top-15 ff-padding-bottom-15 ff-solid-bottom">
				<view class="ff-margin-bottom-15">设备图片</view>
				<view>
					<u-row gutter="20">
						<u-col span="3" v-for="(item, index) of params.devicePics" :key="index">
							<view class="deviceImg ff-margin-bottom-10" @click="previewImgClick(item, 3)">
								<image :src="item" mode="" />
								<view @click.stop="deteleImgClick(index, 3)" class="closeIcon"><u-icon name="close"
										color="#fff" size="22"></u-icon></view>
							</view>
						</u-col>
						<u-col span="3">
							<image @click="upateImgClick(3)"
								src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/upate-icon.png"
								mode="" />
						</u-col>
					</u-row>
				</view>
			</view>
		</view>
		<view>
			<view class="addDevice-but ff-margin-12">
				<u-button @click="deviceSaveClick" type="primary" shape="circle">{{ butTitle }}</u-button>
			</view>
		</view>
		<!-- -----------------------------弹框区------------------------------ -->
		<!-- helangCompress-压缩图片 -->
		<f-compressImg ref="helangCompress" />
		<u-toast ref="uToast" />
		<f-loading ref="loading" />
		<u-modal v-model="locationDeleteImg" @confirm="deleteConfirm" title="温馨提示" show-cancel-button="true"
			:content-style="{ 'line-height': '1.5' }" :content="deleteImgContent" />
	</view>
</template>

<script>
	export default {
		name: 'addDevice',
		data() {
			return {
				// 删除图片弹框系列
				locationDeleteImg: false, // 删除图片弹框显/隐
				deleteImgContent: '', // 删除图片弹框文字提示内容
				deleteIndex: '', // 当前删除的图片index
				deleteType: '', // 当前删除图片的类型
				// 设备选择系列
				deviceState: false, // 设备选择显/隐
				deviceList: [], // 设备种类列表
				// 设备时间选择系列
				timeState: false, // 设备时间选择显/隐
				timeParams: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				// 要提交的内容
				customName: '', // 自定义设备名称
				deviceUrl: '', // 新增/编辑的url
				butTitle: '', // 提交按钮名称
				params: {
					deviceName: '', // 设备名称
					facilitiesDeviceId: '', // 设备ID
					deviceNum: '', // 设备数量
					deviceCode: '', // 设备编码
					deviceBuyTime: '', // 设备购买时间
					certificatePics: [], // 设备证书照片
					invoicePics: [], // 设备发票照片
					devicePics: [], // 设备照片
					deviceId: '' // 设备ID(编辑)
				}
			};
		},
		onLoad(e) {
			// console.log('从上一个页面传过来的参数----', e);
			if (e.deviceId) {
				this.params.deviceId = e.deviceId;
				this.getDeviceDetails(e.deviceId);
				this.butTitle = '更新设备';
			} else {
				this.params.deviceBuyTime = this.getDate(); // 获取当前年月日
				this.butTitle = '添加设备';
			}
			this.geiDevieList(); // 获取设备种类列表数据
		},
		methods: {
			// 获取设备详情
			async getDeviceDetails(deviceId) {
				let that = this;
				that.$refs.loading.openLoading('加载中···'); // 打开loading动画
				const data = await that.$http.get({
					url: `/serviceOrg/device/detail/${deviceId}/v2`
				});
				// console.log('获取设备详情-----', data);
				if (data.code == 200) {
					that.params = data.data;
					this.customName = data.data.deviceName;
					if (this.params.facilitiesDeviceId == 9999) {
						this.params.deviceName = '其它：自定义设备';
					}
					that.params.deviceBuyTime = that.params.deviceBuyTime.slice(0, 10);
				} else {
					that.$refs.uToast.show({
						title: '获取设备详情失败',
						type: 'error'
					});
				}
				that.$refs.loading.closeLoading(); // 关闭loading动画
			},
			// 获取设备种类列表数据
			async geiDevieList() {
				this.$refs.loading.openLoading('加载中···'); // 打开loading动画
				const data = await this.$http.post({
					url: '/serviceOrg/device/queryTemplateDevices'
				});
				// console.log('获取设备种类列表数据-----', data);
				if (data.code == 200) {
					this.deviceList = data.data;
				} else {
					this.$refs.uToast.show({
						title: data.msg,
						type: 'error'
					});
				}
				this.$refs.loading.closeLoading(); // 关闭loading动画
			},
			// 点击选择设备
			deviceClick() {
				if (this.params.deviceId) {
					return
				}
				this.deviceState = true;
			},
			// 选择设备---确定
			deviceConfirm(e) {
				// console.log('当前选择的设备----', e);
				this.params.deviceName = e[0].label;
				this.params.facilitiesDeviceId = e[0].value;

				if (this.params.facilitiesDeviceId == 9999) {
					this.customName = '';
				}
				this.deviceState = false;
			},
			// 设备选择系列--------------------------
			// 获取当前年月日
			getDate() {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			// 设备时间选择---打开弹窗
			timeClick() {
				this.timeState = true;
			},
			// 设备时间选择----确认操作
			confirmTimeClick(e) {
				// console.log('设备时间选择----', e)
				this.params.deviceBuyTime = `${e.year}-${e.month}-${e.day}`;
			},
			// 上传图片(其中包括设备证书，设备发票，设备照片)
			upateImgClick(type) {
				let that = this;
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'], // 拍照 video：视频
					camera: 'back', // 前置摄像头
					sizeType: ['compressed'], // original 原图，compressed 压缩图
					sourceType: ['camera', 'album'],
					success: function(res) {
						that.$refs.loading.openLoading('上传中···'); // 打开loading动画
						that.$refs.helangCompress
							.compress({
								src: res.tempFiles[0].tempFilePath,
								// maxSize: 1080,
								// fileType: 'jpg',
								// quality: 0.85
								// minSize: 640 //最小压缩尺寸，图片尺寸小于该时值不压缩，非H5平台有效。若需要忽略该设置，可设置为一个极小的值，比如负数。
							})
							.then(res => {
								// 压缩成功回调
								// console.log('压缩成功回调', res);
								that.$uploadImg.uploadImgOSS(res, 8).then(res => {
									if (res) {
										if (type == 1) {
											that.$refs.loading.closeLoading(); // 关闭loading动画
											that.$refs.uToast.show({
												title: '上传成功',
												type: 'success'
											});
											that.params.certificatePics.push(res);
											return;
										}
										if (type == 2) {
											that.$refs.loading.closeLoading(); // 关闭loading动画
											that.$refs.uToast.show({
												title: '上传成功',
												type: 'success'
											});
											that.params.invoicePics.push(res);
											return;
										}
										if (type == 3) {
											that.$refs.loading.closeLoading(); // 关闭loading动画
											that.$refs.uToast.show({
												title: '上传成功',
												type: 'success'
											});
											that.params.devicePics.push(res);
											return;
										}
									} else {
										that.$refs.loading.closeLoading(); // 关闭loading动画
										that.$refs.uToast.show({
											title: '上传失败，请重新上传',
											type: 'error'
										});
									}
								});
							})
							.catch(err => {
								// 压缩失败回调
								// console.log('压缩失败回调', err);
								that.$refs.loading.closeLoading(); // 关闭loading动画
								that.$refs.uToast.show({
									title: '上传失败，请重新上传！',
									type: 'error'
								});
							});
					}
				});
			},
			// 删除图片(其中包括设备证书，设备发票，设备照片)
			deteleImgClick(index, type) {
				this.deleteIndex = index;
				this.deleteType = type;
				if (type == 1) {
					this.deleteImgContent = '您确定删除“设备证书”的这张图片吗？';
					this.locationDeleteImg = true;
					return;
				}
				if (type == 2) {
					this.deleteImgContent = '您确定删除这张“设备发票图片”吗？';
					this.locationDeleteImg = true;
					return;
				}
				if (type == 3) {
					this.deleteImgContent = '您确定删除这张“设备图片”吗？';
					this.locationDeleteImg = true;
					return;
				}
			},
			// 删除图片----确定操作
			deleteConfirm() {
				if (this.deleteType == 1) {
					this.$refs.uToast.show({
						title: '删除成功',
						type: 'success'
					});
					this.params.certificatePics.splice(this.deleteIndex, 1);
					return;
				}
				if (this.deleteType == 2) {
					this.$refs.uToast.show({
						title: '删除成功',
						type: 'success'
					});
					this.params.invoicePics.splice(this.deleteIndex, 1);
					return;
				}
				if (this.deleteType == 3) {
					this.$refs.uToast.show({
						title: '删除成功',
						type: 'success'
					});
					this.params.devicePics.splice(this.deleteIndex, 1);
					return;
				}
			},
			// 预览图片(其中包括设备证书，设备发票，设备照片)
			previewImgClick(item, type) {
				if (type == 1) {
					uni.previewImage({
						urls: this.params.certificatePics,
						current: item
					});
				}
				if (type == 2) {
					uni.previewImage({
						urls: this.params.invoicePics,
						current: item
					});
				}
				if (type == 3) {
					uni.previewImage({
						urls: this.params.devicePics,
						current: item
					});
				}
			},
			// 增加or更新设备
			deviceSaveClick() {
				if (!this.params.deviceName) {
					this.$refs.uToast.show({
						title: '设备名称不能为空',
						type: 'error'
					});
					return;
				}
				if (this.params.facilitiesDeviceId == 9999 && this.customName == '') {
					this.$refs.uToast.show({
						title: '自定义设备名称不能为空',
						type: 'error'
					});
					return;
				}
				if (this.params.facilitiesDeviceId == 9999) {
					this.params.deviceName = '其它：' + this.customName;
				}
				if (!this.$check.numberNoZeroPosiReg(this.params.deviceNum)) {
					this.$refs.uToast.show({
						title: '设备数量必须是不为0的整数',
						type: 'error'
					});
					return;
				}
				if (this.params.deviceId) {
					this.deviceUrl = '/serviceOrg/device/upd/v3'; // 编辑
				} else {
					this.deviceUrl = '/serviceOrg/device/add/v3'; // 新增
				}
				this.$refs.loading.openLoading('提交中···'); // 打开loading动画
				this.$http.post({
					url: this.deviceUrl,
					data: this.params
				}).then(res => {
					// console.log('保存设备返回的数据-------', res);
					this.$refs.loading.closeLoading(); // 关闭loading动画
					if (res.code == 200) {
						this.$refs.uToast.show({
							title: res.msg,
							type: 'success'
						});
						setTimeout(() => {
							// 刷新前一个页面 （配合前页面的onShow使用）
							uni.$emit("getlist", {}) //这里可以传个空,也可以传值过去
							uni.navigateBack({ // 返回上一页
								delta: 1
							})
						}, 500);
						// this.$pageJump.reLaunch('/pages/maintenance/mechanism/home/components/deviceManagement/deviceManagement');
					} else {
						this.$refs.uToast.show({
							title: res.msg,
							type: 'error'
						});
					}
				});
			}
		},
		onShareAppMessage() {
			return {
				title: '分享小程序给朋友',
				path: '/pages/homePage/Home'
			};
		}
	};
</script>

<style lang="scss" scoped>
	.addDevice {
		image {
			width: 100%;
			height: 140rpx;
		}

		.deviceImg {
			position: relative;
		}

		&-but {
			margin-top: 100rpx;
			width: 90%;
			margin: 10% 5%;

			/deep/.u-size-default {
				height: 90rpx !important;
				line-height: 90rpx !important;
			}
		}
	}
</style>